<?php

/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */

function dt_log_push($data) {
	//return;
	$myFile = "apns-logs-" . date("j-n-Y") . ".txt";
    $fh = fopen($myFile, 'a');
    $stringData = "$data\n";
    fwrite($fh, $stringData);
    fclose($fh);
}

function dt_set_device_token_for_user_id($user_id, $device_token, $pro, $env) {
    $user_id = mysql_real_escape_string($user_id);
    $device_token = mysql_real_escape_string($device_token);
    if (!$user_id || strlen($device_token) < 10) {
        return FALSE;
    }
    $timestamp = time();
    $query = "INSERT INTO draw_together_device_tokens (user_id, device_token, pro, env, timestamp)
                VALUES ('$user_id', '$device_token', '$pro', '$env', '$timestamp')";
    //echo $query;
    return safe_insert_query($query);
}

function dt_unset_device_token_for_user_id($user_id, $device_token, $pro, $env) {
    $user_id = mysql_real_escape_string($user_id);
    $device_token = mysql_real_escape_string($device_token);
    if (!$user_id || strlen($device_token) < 10) {
        return FALSE;
    }
    $timestamp = time();
    $query = "DELETE FROM draw_together_device_tokens WHERE user_id = '$user_id' AND device_token = '$device_token' AND env = '$env' AND pro = '$pro'";
    return safe_delete_query($query);
}

function dt_get_device_tokens_for_user_id($user_id) {
    $user_id = mysql_real_escape_string($user_id);
    $query = "SELECT device_token, pro, env FROM draw_together_device_tokens WHERE user_id = '$user_id' ORDER BY timestamp DESC";
    //$tokens = array();
    //echo $query;
    $results = safe_select_query($query);
    return $results;
    /*
    foreach($results as $result) {
        $tokens[] = $result->device_token;
    }
    //var_dump($tokens);
    return $tokens;
     * 
     */
}

function passphrase($dev, $pro) {
    return $dev ? "greengar" : "greengar";
}

function appcert($dev, $pro) {
    if($pro) {
        return $dev ? (dirname(__FILE__) . '/ckpro.pem') : (dirname(__FILE__) . '/ckproas.pem');
    }
    return $dev ? (dirname(__FILE__) . '/ck.pem') : (dirname(__FILE__) . '/ckas.pem');
}

function sslserver($dev) {
    return $dev ? "ssl://gateway.sandbox.push.apple.com:2195" : "ssl://gateway.push.apple.com:2195";
}

function dt_send_push_notification($user_id, $message, $dev) {
    dt_log_push("Attempt to push ($user_id, $message, $dev)");
    $passphrase = passphrase($dev);
    $deviceTokens = dt_get_device_tokens_for_user_id($user_id);
    if (!$deviceTokens || !is_array($deviceTokens) || count($deviceTokens) <= 0) {
    	dt_log_push("Cannot find device_tokens");
        return FALSE;
    }
    
    ////////////////////////////////////////////////////////////////////////////////
    foreach ($deviceTokens as $deviceToken) {
        
        // dev = 1, env = 1
        // env = 1 is DEBUG
        // env = 0 is APPSTORE
        $env = $deviceToken->env;
        if($dev != $env) {
            continue;
        }
        $pro = $deviceToken->pro;
        $ck = appcert($dev, $pro);
        $ctx = stream_context_create();
        stream_context_set_option($ctx, 'ssl', 'local_cert', $ck);
        stream_context_set_option($ctx, 'ssl', 'passphrase', $passphrase);
        // Open a connection to the APNS server
        $fp = stream_socket_client(
                sslserver($dev), $err,
                $errstr, 60, STREAM_CLIENT_CONNECT|STREAM_CLIENT_PERSISTENT, $ctx);
        if (!$fp) {
        	$server = sslserver($dev);
            //exit("Failed to connect: $err $errstr" . PHP_EOL);
            dt_log_push("Failed to connect($ck, $passphrase, $server): $err $errstr");
            return FALSE;
        }

        //echo 'Connected to APNS' . PHP_EOL;
		dt_log_push('Connected to APNS');
        // Create the payload body
        $body['aps'] = array(
                'alert' 	=> $message,
                'sound' 	=> 'default',
                'push_id'	=> $push_id
                );

        // Encode the payload as JSON
        $payload = json_encode($body);
    
    //foreach ($deviceTokens as $deviceToken) {
    
        // Build the binary notification
        $msg = chr(0) . pack('n', 32) . pack('H*', $deviceToken->device_token) . pack('n', strlen($payload)) . $payload;

        // Send it to the server
        $result = fwrite($fp, $msg, strlen($msg));
    
    //}
    
    if (!$result) {
            //echo 'Message not delivered' . PHP_EOL;
            dt_log_push('Message not delivered');
    }
    else {
            //echo 'Message successfully delivered' . PHP_EOL;
            dt_log_push('Message successfully delivered');
    }
    
    // Close the connection to the server
    
        fclose($fp);
    }
    
    return TRUE;
}

?>
